<template>
  <div>
    <div class="bg_fff p_14 pb_0 mb_12">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="" prop="keyword">
          <el-input
            style="width: 180px"
            v-model="queryParams.keyword"
            placeholder="请输入优惠活动名称/ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型名称" prop="task_id">
          <el-select
            style="width: 160px"
            v-model="queryParams.task_id"
            placeholder="请选择类型名称"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="dict in taskList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="times">
          <el-date-picker
            v-model="times"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="admin">
          <el-select filterable
            style="width: 160px"
            v-model="queryParams.admin"
            placeholder="请选择创建人"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="dict in adminList"
              :key="dict.id"
              :label="dict.user_login"
              :value="dict.user_login"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当前状态" prop="status">
          <el-select
            style="width: 160px"
            v-model="queryParams.status"
            placeholder="请选择当前状态"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="dict in statusList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="bg_fff boxflex">
      <div
        class="flexrowbetween flexwrapper mb_15"
        style="align-items: flex-start"
      >
        <div class="flex">
          <el-button
            plain
            type="primary"
            class="bg_fff mr_5 f-14 c_primary"
            size="mini"
            @click="selectAll"
            >全选</el-button
          >
          <el-button
            plain
            type="primary"
            class="bg_fff f-14 c_primary"
            size="mini"
            @click="selectInvert"
            >反选</el-button
          >
          <el-button
            type="primary"
            class="f-14"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['promotionalActivities:add']"
            >新增</el-button
          >
        </div>
        <div>
          <el-button type="danger" :disabled='multiple' size="mini" class="f-14 mr_10" @click="handleDeleteAll"  v-hasPermi="['promotionalActivities:delAll']">删除</el-button>
          <el-button plain type="primary"  class="f-14 mr_10" size="mini"  @click="handleExport"
                     v-hasPermi="['promotionalActivities:export']"
          >导出</el-button>
          <el-dropdown trigger="click" class="mr_10">
            <el-button type="primary" size="mini" class="f-14"  v-hasPermi="['promotionalActivities:customList']">
              自定义列表
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <div class="dropbody">
                <el-checkbox-group v-model="checkedOption" class="flexcolumn" @change="changeSelect">
                  <el-checkbox v-for="(item,index) in selectoptions" :label="item.label" :key="index" class="m_5">{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        ref="tablelayout"
        class="commtable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" align="center" v-if="discountsOption.includes('序号')">
          <template slot-scope="scope">
            <span>{{ (queryParams.page - 1) * queryParams.num + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态开关" prop="id" width="120" v-if="discountsOption.includes('状态开关')">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus($event,scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('类型名称')"
          align="center"
          label="类型名称"
          prop="name"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.package">{{scope.row.package.name||'-'}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('优惠活动ID')"
          align="center"
          min-width="120"
          label="优惠活动ID"
          prop="id"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column v-if="discountsOption.includes('优惠活动名称')"
          align="center"
          label="优惠活动名称"
          min-width="120"
          prop="name"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column v-if="discountsOption.includes('广告币数量（个）')"
          align="center"
          label="广告币数量（个）"
          prop="score"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.score || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('返现数量（个）')"
          align="center"
          label="返现数量（个）"
          prop="role_user.role.name"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.give_score || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('单价(人民币)')"
          align="center"
          label="单价(人民币)"
          prop="coin"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.coin || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('总成交单量')"
          align="center"
          label="总成交单量"
          prop="data.count"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.data">{{ scope.row.data.count}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('成交总额(人民币)')"
          align="center"
          label="成交总额(人民币)"
          prop="data.coin"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.data">{{ scope.row.data.coin}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('备注')"
          align="center"
          label="备注"
          prop="msg"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.msg||'-'}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('创建时间')"
          align="center"
          label="创建时间"
          prop="create_time"
          min-width="150"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.create_time || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="discountsOption.includes('创建人')"
          align="center"
          label="创建人"
          prop="name"
          min-width="100"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.admin">{{
              scope.row.admin.user_login || "-"
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" :show-overflow-tooltip="true" align="center" v-if="discountsOption.includes('状态')">
          <template slot-scope="scope">
            <div v-if="scope.row.status==1">
              <span class="succdot mr_5"></span>开启
            </div>
            <div v-else>
              <span class="dangerdot mr_5"></span>暂停
            </div>
            <!-- <span v-else class="dangerdot mr_5"></span> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="操作"
          width="160"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <div class="flexcenter btnflex">
              <div class="commhover mr_10" @click="handleUpdate(scope.row)"  v-hasPermi="['promotionalActivities:edit']">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top-start"
                >
                  <i class="el-icon-edit-outline f-24 c_primary"></i>
                </el-tooltip>
              </div>
              <div class="commhover mr_10" @click="handleDelete(scope.row)" v-hasPermi="['promotionalActivities:del']">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-start"
                >
                  <i class="el-icon-delete c_F11616 f-24"></i>
                </el-tooltip>
              </div>
              <div
                class="commhover"
                @click="changeStatus(0,scope.row)"
                v-if="scope.row.status == 1"
                v-hasPermi="['promotionalActivities:stop']"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="暂停"
                  placement="top-start"
                >
                  <svg-icon class-name="f-24 " icon-class="pause" />
                </el-tooltip>
              </div>

              <div
                class="commhover"
                @click="changeStatus(1,scope.row)"
                v-hasPermi="['promotionalActivities:open']"
                v-if="scope.row.status == 0"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="启用"
                  placement="top-start"
                >
                  <svg-icon class-name="f-24 c_12A000" icon-class="start1" />
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.num"
        @pagination="getList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="620px"
      class="commdia"
      :before-close="handleClose"
      :close-on-click-modal='false'
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="类型：" prop="package_id">
          <el-select
            style="width: 90%"
            v-model="form.package_id"
            placeholder="请选择类型"
            clearable
          >
            <el-option
              v-for="dict in taskList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" style="width:90%" />
        </el-form-item>
        <el-form-item label="广告币数量：" prop="score">
          <el-input v-model="form.score" type="number" placeholder="请输入广告币数量" style="width:90%" /> 个
        </el-form-item>
        <el-form-item label="返现数量：" prop="give_score">
          <el-input v-model="form.give_score" type="number" placeholder="请输入返现数量" style="width:90%"  /> 个
        </el-form-item>
        <el-form-item label="单价：" prop="coin">
          <el-input v-model="form.coin" type="number" placeholder="请输入单价" style="width:90%"  /> 元
        </el-form-item>
        <el-form-item label="备注：" prop="msg">
          <el-input v-model="form.msg" type="textarea" placeholder="请输入备注" style="width:90%"  />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading='subloading' @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  getUserList,
  taskIndex,
  createTask,
  editTask,
  statusTaskOpen,
  statusTaskClose,
  deleteTaskAll,
  deleteTask, reqTaskIndexExport
} from '@/api/favorable'
export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
        admin: "",
        keyword: "",
        status: "",
        task_id: "",
      },
      times: "",
      adminList: [],
      taskList: [],
      statusList: [
        { name: "开启", id: 1 },
        { name: "暂停", id: 0 },
      ],
      loading: false,
      tableData: [],
      total: 0,
      checkedOption: [],
      selectoptions: [
        { id: 1, label: "序号" },
        { id: 2, label: "状态开关" },
        { id: 3, label: "类型名称" },
        { id: 5, label: "优惠活动ID" },
        { id: 6, label: "优惠活动名称" },
        { id: 7, label: "广告币数量（个）" },
        { id: 8, label: "返现数量（个）" },
        { id: 9, label: "单价（人民币）" },
        { id: 10, label: "总成交单量" },
        { id: 11, label: "成交总额(人民币)" },
        { id: 15, label: "备注" },
        { id: 12, label: "创建时间" },
        { id: 13, label: "创建人" },
        { id: 14, label: "状态" },
      ],
      paramsForm:{},
      exportColumns: [
        {key: 'package.name', label: `类型名称`,},
        {key: 'id', label: `优惠活动ID`},
        {key: 'name', label: `优惠活动名称`,},
        {key: 'score', label: `广告比数量（个）`},
        {key: 'give_score', label: `返现数量（个）`,},
        {key: 'coin', label: `单价(人民币)`,},
        {key: 'data.count', label: `总成交单量`,},
        {key: 'data.coin', label: `成交总额(人民币)`,},
        {key: 'msg', label: `备注`,},
        {key: 'create_time', label: `创建时间`,},
        {key: 'admin.user_login', label: `创建人`,},
        {key: 'status_name', label: `状态`,},
      ],
      rowids: [],
      multiple: true,
      form:{},
      rules:{
        package_id:[{ required: true, message: '请选择类型', trigger: 'change' }],
        name:[{ required: true, message: '请输入名称', trigger: 'blur' }],
        score:[{ required: true, message: '请输入广告币数量', trigger: 'blur' }],
        give_score:[{ required: true, message: '请输入返现数量', trigger: 'blur' }],
        coin:[{ required: true, message: '请输入单价', trigger: 'blur' }],
      },
      open:false,
      title:'',
      subloading:false,
    };
  },
  created() {
    let discountsOption = JSON.parse(localStorage.getItem("discountsOption"));
    if (discountsOption) {
      this.changeSelect(discountsOption);
    }
    this.checkedOption = this.discountsOption;
    this.getDicts('/manager/api/getPackageList').then(res=>{
      this.taskList = res.data
    })
    this.getUserList()
    this.getList();
  },
  computed: {
    ...mapState({
      discountsOption: (state) => state.paramsoption.discountsOption,
    }),
  },
  methods: {
    handleExport() {
      let form = JSON.parse(JSON.stringify(this.paramsForm))
      let head = []
      let keys = []
      this.exportColumns.forEach(item => {
        this.checkedOption.forEach(sitem => {
          if (sitem == item.label) {
              head.push(item.label)
              keys.push(item.key)

          }
        })
      })
      form.head = head
      form.keys = keys
      delete form.page
      delete form.num
      reqTaskIndexExport(form).then((res) => {
        console.log('333', res)
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '套餐活动作者列表数据.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })

    },
    getUserList(){
      getUserList().then(res=>{
        this.adminList = res.data
      })
    },
    getList() {
      this.loading = true;
      let params = {
        page: this.queryParams.page,
        num: this.queryParams.num,
      };
      if (this.queryParams.keyword) {
        params.keyword = this.queryParams.keyword;
      }
      if (this.queryParams.status || this.queryParams.status === 0) {
        params.status = this.queryParams.status;
      }
      if (this.queryParams.admin) {
        params.admin = this.queryParams.admin;
      }
      if (this.queryParams.task_id) {
        params.task_id = this.queryParams.task_id;
      }
      if (this.times && this.times.length) {
        params.start = this.times[0];
        params.end = this.times[1];
      }
      this.paramsForm=params;
      taskIndex(params).then((response) => {
        this.tableData = response.data.list;
        this.total = response.data.count;
        this.loading = false;
      });
      this.loading = false;
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    changeSelect(arr) {
      this.$store.commit("SET_DISCOUNTSOPTION", arr);
      this.$nextTick(() => {
        //在数据加载完，重新渲染表格
        this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
      });
    },

    handleSelectionChange(selection) {
      this.rowids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    selectAll() {
      //全选功能,先进行清除状态，然后再选择是全选还是多选
      this.$refs.tablelayout.clearSelection();
      this.tableData.forEach((row) => {
        this.$refs.tablelayout.toggleRowSelection(row);
      })
    },

    selectInvert() {
      //反选
      let listfiter = this.tableData.filter(item => {
        return this.rowids.indexOf(item.id) == -1;// 不包含选中的
      });
      this.$refs.tablelayout.clearSelection();
      if (listfiter && listfiter.length > 0) {
        listfiter.forEach((item) => {
          this.$refs.tablelayout.toggleRowSelection(item);
        })
      }
    },

    handleDelete(row){
      this.$modal.confirm('确定删除该条活动？').then(()=>{
        return deleteTask({
          id:row.id
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },

    handleDeleteAll(){
      this.$modal.confirm('确定删除选中的活动？').then(()=>{
        return deleteTaskAll({
          id:this.rowids
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },

    changeStatus(val,row){
      if(val){
        this.$modal.confirm('是否开启该条活动').then(function() {
          return statusTaskOpen({
            id:row.id
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess('开启成功');
        }).catch(() => {
          row.status =  0
        });
      }else{
        this.$modal.confirm('是否暂停该条活动').then(function() {
          return statusTaskClose({
            id:row.id
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("暂停成功");
        }).catch(() => {
          row.status = 1
        });
      }

    },

    reset(){
      this.form = {
        id:undefined,
        package_id:'',
        name:"",
        score:'',
        give_score:'',
        coin:'',
        msg:'',
        status:1,
      }
    },

    handleAdd() {
      this.reset()
      this.title = '新增'
      this.open = true
    },

    handleUpdate(row){
      this.reset()
      this.title = '编辑'
      this.form.id = row.id
      this.form.package_id = row.package_id
      this.form.score = row.score
      this.form.coin = row.coin
      this.form.give_score = row.give_score
      this.form.name = row.name
      this.form.status = row.status
      this.form.msg = row.msg
      this.open = true
    },

    handleClose(){
      this.open = false
    },

    handleSubmit(){
      this.$refs.form.validate(valid=>{
        if(!valid) return
        this.subloading = true
        if(this.form.id){
          editTask(this.form).then(()=>{
            this.handleClose()
            this.$message.success('编辑成功')
            this.subloading = false
            this.getList()
          }).catch(()=>{
            this.subloading = false
          })
        }else{
          createTask(this.form).then(()=>{
            this.handleClose()
            this.$message.success('新增成功')
            this.subloading = false
            this.getList()
          }).catch(()=>{
            this.subloading = false
          })
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.incomebox {
  width: 100%;
  height: 95px;
  padding: 0 30px;
  background: url("~@/assets/images/fin_bg.png") 100% 100% no-repeat;
  background-size: cover;
}
.l_img {
  width: 62px;
  height: 55px;
}
.boxflex {
  padding: 16px 20px;
  .line {
    width: 2px;
    height: 18px;
    background-color: #1670f1;
  }
}
</style>
